package com.example.mansystem.Interceptor;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.mansystem.Annotation.RequiredApi;
import com.example.mansystem.dto.LoginDto;
import com.example.mansystem.exception.CodeAndMsg;
import com.example.mansystem.exception.UserDefinedException;
import com.example.mansystem.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.lang.Nullable;
import org.springframework.util.CollectionUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

public class SessionHandlerInterceptor implements HandlerInterceptor {
    @Autowired
    UserService userService;
    /**
     * Controller处理前
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     * @param handler 处理对象
     * @return true or false
     * @throws Exception 异常
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        HttpSession session = request.getSession();
        if(session==null)
        {
            throw new UserDefinedException(CodeAndMsg.NOTLOGIN);
        }

        String userLogin =(String) session.getAttribute("username");

        if(userLogin ==null)
        {
            throw new UserDefinedException(CodeAndMsg.NOTLOGIN);
        }

        if(!this.hasPermission(handler,userLogin))
        {
            throw new UserDefinedException(CodeAndMsg.DoesntHasApiPermission);
        }


        return true;
    }

    private boolean hasPermission(Object handler,String username) {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            // 获取方法上的注解
            RequiredApi requiredApi = handlerMethod.getMethod().getAnnotation(RequiredApi.class);
            // 如果方法上的注解为空 则获取类的注解
            if (requiredApi == null) {
                requiredApi = handlerMethod.getMethod().getDeclaringClass().getAnnotation(RequiredApi.class);
            }
            // 如果注解为null, 说明不需要拦截, 直接放过
            if (requiredApi == null) {
                return true;
            }
            // 如果标记了注解，则判断权限
            if (StringUtils.isNotBlank(requiredApi.value())) {
                List<String> permissionList= userService.getUserApi(username);


                if (permissionList.isEmpty() ){
                    return false;
                }
                return permissionList.contains(requiredApi.value());
            }
        }
        return true;
    }


    /**
     * Controller方法处理完毕后，调用此方法
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     * @param handler 处理对象
     * @param modelAndView 视图
     * @throws Exception 异常
     */


    /**
     * 页面渲染完毕后调用此方法，通常用来清除某些资源，类似Java语法的finally
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     * @param handler 处理对象
     * @param ex 异常
     * @throws Exception 异常
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {

    }

}
